<template>
  <div>
    <div>
      <h1>商品列表</h1>
    </div>
    <div>
      <el-form :inline="true" :model="searchForm" class="demo-form-inline">
        <el-form-item label="关键字">
          <el-input
            v-model="searchForm.keyWord"
            placeholder="请选择id/spu/商品名称"
            clearable
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="loadProdList()">查询</el-button>
          <el-button type="danger" @click="ondeleteByIds()">批量删除</el-button>
          <el-button type="success" @click="onAddProd()">添加</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div>
      <el-table
        :data="prodList"
        border
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="prodId" label="商品Id" />
        <el-table-column prop="prodSpu" label="商品spu" />
        <el-table-column prop="kindName" label="种类" />
        <el-table-column prop="typeName" label="类型" />
        <el-table-column prop="prodName" label="商品名称" />
        <el-table-column prop="brandName" label="品牌" />
        <el-table-column prop="unitName" label="单位" />
        <el-table-column prop="tagName" label="标签" />
        <el-table-column prop="appr" label="供应商" />
        <el-table-column prop="prodImage" label="图片">
          <template #default="scoped">
            <el-image
              v-if="scoped.row.prodImage != null"
              :src="scoped.row.prodImage"
              style="width: 70px; height: 70px"
            ></el-image>
          </template>
        </el-table-column>
        <el-table-column prop="createBy" label="创作人" />
        <el-table-column prop="createTime" label="创作时间" />
        <el-table-column label="操作">
          <template #default="scope">
            <el-button
              v-if="scope.row.prodStatus == 2"
              size="small"
              type="primary"
              @click="toProdDetail(scope.row.prodId)"
              >商品详情</el-button
            >
            <el-button
              v-if="scope.row.prodStatus == 2"
              size="small"
              type="success"
              @click="onAddProdAtta(scope.row)"
              >商品附件</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div>
      <el-pagination
        v-model:current-page="searchForm.pageNum"
        v-model:page-size="searchForm.pageSize"
        :page-sizes="[2, 3, 4, 5]"
        :background="true"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    <div>
      <el-dialog v-model="dialogFormVisible" title="添加商品" width="800px">
        <el-form :model="form" :rules="rules" ref="ruleFormRef">
          <el-form-item
            label="商品类型"
            :label-width="formLabelWidth"
            prop="prodKind"
          >
            <el-radio-group v-model="form.prodKind">
              <el-radio
                v-for="item in deptList"
                :value="item.dictValue"
                :label="item.dictName"
                :key="item.dictType"
                size="small"
              ></el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item
            label="商品分类"
            :label-width="formLabelWidth"
            prop="prodType"
          >
            <el-tree-select
              v-model="form.prodType"
              :data="typeList"
              :render-after-expand="false"
              style="width: 240px"
            />
          </el-form-item>
          <el-form-item
            label="商品spu"
            :label-width="formLabelWidth"
            prop="prodSpu"
          >
            <el-input v-model="form.prodSpu" autocomplete="off" />
          </el-form-item>
          <el-form-item
            label="商品名称"
            :label-width="formLabelWidth"
            prop="prodName"
          >
            <el-input v-model="form.prodName" autocomplete="off" />
          </el-form-item>
          <el-form-item label="商品品牌" :label-width="formLabelWidth">
            <el-select v-model="form.brandId" placeholder="请选择商品品牌">
              <el-option
                v-for="item in brandList"
                :value="item.brandId"
                :label="item.brandName"
                :key="item.brandId"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            label="商品单位"
            :label-width="formLabelWidth"
            prop="unitId"
          >
            <el-select v-model="form.unitId" placeholder="请选择单位">
              <el-option
                v-for="item in unitList"
                :value="item.dictValue"
                :label="item.dictName"
                :key="item.dictType"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="商品标签" :label-width="formLabelWidth">
            <el-select v-model="form.tagId" placeholder="请选择标签">
              <el-option
                v-for="item in tagList"
                :value="item.dictValue"
                :label="item.dictName"
                :key="item.dictType"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="供应商" :label-width="formLabelWidth">
            <el-input v-model="form.appr" autocomplete="off" />
          </el-form-item>
          <el-form-item
            label="缩略图"
            :label-width="formLabelWidth"
            prop="prodImage"
          >
            <el-upload
              class="avatar-uploader"
              action="http://localhost:10010/prod/type/uploadFile"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :headers="headers"
            >
              <img v-if="form.prodImage" :src="form.prodImage" class="avatar" />
              <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            </el-upload>
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取消</el-button>
            <el-button type="primary" @click="submitForm(ruleFormRef)">
              确定
            </el-button>
          </div>
        </template>
      </el-dialog>
    </div>
    <div>
      <el-dialog
        v-model="dialogAttaFormVisible"
        title="添加商品附件"
        width="800"
      >
        <el-form ref="ruleFormRef" :model="attaForm" :rules="attarules">
          <el-form-item label="商品轮播图" :label-width="formLabelWidth">
            <el-upload
              v-model:file-list="fileImagesList"
              action="http://localhost:10010/prod/type/uploadFile"
              list-type="picture-card"
              :on-preview="handlePictureCardPreview"
              :on-remove="handleRemove"
              :headers="headers"
            >
              <el-icon><Plus /></el-icon>
            </el-upload>

            <el-dialog v-model="dialogVisible">
              <img
                w-full
                :src="attaForm.attaImages"
                alt="attaForm.attaImages"
              />
            </el-dialog>
          </el-form-item>
          <el-form-item label="商品视屏" :label-width="formLabelWidth">
            <el-upload
              v-model:file-list="fileVideoList"
              class="upload-demo"
              action="http://localhost:10010/prod/type/uploadFile"
              multiple
              :on-preview="handlePreview"
              :on-remove="handleVidioRemove"
              :limit="3"
              :headers="headers"
            >
              <el-button type="primary">上传视屏</el-button>
              <template #tip>
                <div class="el-upload__tip">jpg/png文件不能大于500k.</div>
              </template>
            </el-upload>
          </el-form-item>
          <el-form-item
            label="上架时间"
            prop="upFlag"
            :label-width="formLabelWidth"
          >
            <el-radio-group v-model="attaForm.upFlag">
              <el-radio :value="0" size="small">立即上架</el-radio>
              <el-radio :value="1" size="small">定时上架</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item :label-width="formLabelWidth">
            <el-date-picker
              v-if="attaForm.upFlag == 1"
              v-model="attaForm.upTime"
              type="datetime"
              placeholder="请选择定时上架时间"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>
          <el-form-item label="下架时间" :label-width="formLabelWidth">
            <el-switch
              v-model="attaForm.downFlag"
              size="small"
              :active-value="1"
              :inactive-value="0"
              active-text="定时下架"
              inactive-text="立即下架"
            />
          </el-form-item>
          <el-form-item :label-width="formLabelWidth">
            <el-date-picker
              v-if="attaForm.downFlag == 1"
              v-model="attaForm.downTime"
              type="datetime"
              placeholder="请选择定时下架时间"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="dialogAttaFormVisible = false">放弃</el-button>
            <el-button type="primary" @click="submitattaForm(ruleFormRef)">
              添加
            </el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref } from "vue";
import {
  getProdList,
  deleteByIds,
  getDictList,
  getBrandList,
  selectType,
  addProd,
  addProdAtta,
} from "../api/api";
import { ElMessage, ElMessageBox } from "element-plus";
import { Plus } from "@element-plus/icons-vue";
import type { FormInstance, FormRules } from "element-plus";
import type { UploadProps, UploadUserFile } from "element-plus";
import { useRouter } from "vue-router";

const router = useRouter();
const fileImagesList = ref([]);
const fileVideoList = ref([]);

const ruleFormRef = ref<FormInstance>();
const dialogFormVisible = ref(false);
const dialogAttaFormVisible = ref(false);
const formLabelWidth = "140px";
const headers = ref({
  token: sessionStorage.getItem("token"),
});
const deptList = ref([]);
const typeList = ref([]);
const brandList = ref([]);
const tagList = ref([]);
const unitList = ref([]);
const form = ref({
  appr: "",
  brandId: null,
  prodId: null,
  prodImage: "",
  prodKind: null,
  prodName: "",
  prodSpu: "",
  prodType: null,
  tagId: null,
  unitId: null,
});
const prodList = ref([]);
const total = ref(0);
const searchForm = ref({
  pageNum: 1,
  pageSize: 2,
  keyWord: null,
});
const brandForm = ref({
  pageNum: 1,
  pageSize: 99999,
});
//分页
const handleSizeChange = (val: number) => {
  console.log(`${val} items per page`);
  searchForm.value.pageSize = val;
  loadProdList();
};
const handleCurrentChange = (val: number) => {
  console.log(`current page: ${val}`);
  searchForm.value.pageNum = val;
  loadProdList();
};
//商品详情
const toProdDetail = (prodId: number) => {
  router.push("/prodDetail/" + prodId);
};
//获取商品列表
const loadProdList = () => {
  getProdList(searchForm.value).then((res) => {
    if (res.data.code == 200) {
      prodList.value = res.data.data.records;
      total.value = res.data.data.total;
    }
  });
};
//添加附件校验
const attarules = ref<FormRules>({
  upFlag: [{ required: true, message: "上架时间不能为空", trigger: "blur" }],
  attaImages: [
    {
      required: true,
      validator: (rule: any, value: any, callback: any) => {
        if (!value) {
          return callback(new Error("图片不能为空"));
        } else {
          callback();
        }
      },
    },
  ],
});

const submitattaForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      //获取轮播图
      const attaImageList = ref([]);
      fileImagesList.value.forEach((item) => {
        attaImageList.value.push(item.response.data);
      });
      attaForm.value.attaImages = JSON.stringify(attaImageList.value);
      //获取视频
      if (fileVideoList.value.length <= 0) {
        ElMessage.error("请上传视屏");
      }
      attaForm.value.attaVideo = fileVideoList.value[0].response.data;

      addProdAtta(attaForm.value).then((res) => {
        if (res.data.code == 200) {
          ElMessage.success("添加成功");
          dialogAttaFormVisible.value = false;
        } else {
          ElMessage.error(res.data.msg);
        }
      });
    } else {
      console.log("error submit!", fields);
    }
  });
};
//上传视屏
const handleVidioRemove: UploadProps["onRemove"] = (file, uploadFiles) => {
  console.log(file, uploadFiles);
};

const handlePreview: UploadProps["onPreview"] = (uploadFile) => {
  console.log(uploadFile);
};

//上传缩略图
const dialogVisible = ref(false);
const handleRemove: UploadProps["onRemove"] = (uploadFile, uploadFiles) => {
  console.log(uploadFile, uploadFiles);
};

const handlePictureCardPreview: UploadProps["onPreview"] = (uploadFile) => {
  attaForm.value.attaImages = uploadFile.url!;
  dialogVisible.value = true;
};
//添加商品附件
const attaForm = ref({
  attaId: null,
  attaImages: "",
  attaVideo: "",
  downFlag: null,
  downTime: "",
  prodId: null,
  upFlag: null,
  upTime: "",
});
const onAddProdAtta = (row: any) => {
  attaForm.value = {
    attaId: null,
    attaImages: "",
    attaVideo: "",
    downFlag: null,
    downTime: "",
    prodId: null,
    upFlag: null,
    upTime: "",
  };
  fileImagesList.value = [];
  fileVideoList.value = [];
  attaForm.value.prodId = row.prodId;
  dialogAttaFormVisible.value = true;
};
//校验
const rules = ref<FormRules>({
  prodKind: [{ required: true, message: "种类不能为空", trigger: "blur" }],
  prodSpu: [{ required: true, message: "spu不能为空", trigger: "blur" }],
  prodName: [{ required: true, message: "名称不能为空", trigger: "blur" }],
  prodType: [{ required: true, message: "分类不能为空", trigger: "blur" }],
  unitId: [{ required: true, message: "单位不能为空", trigger: "blur" }],
  prodImage: [{ required: true, message: "缩略图不能为空", trigger: "blur" }],
});

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      addProd(form.value).then((res) => {
        if (res.data.code == 200) {
          ElMessage.success("添加成功");
          dialogFormVisible.value = false;
          loadProdList();
        } else {
          ElMessage.error(res.data.msg);
        }
      });
    } else {
      console.log("error submit!", fields);
    }
  });
};
//上传图片
const handleAvatarSuccess: UploadProps["onSuccess"] = (
  response,
  uploadFile
) => {
  form.value.prodImage = URL.createObjectURL(uploadFile.raw!);
};

//批量删除
const multipleSelection = ref<any[]>([]);
const handleSelectionChange = (val: any[]) => {
  multipleSelection.value = val;
};
const ondeleteByIds = () => {
  if (multipleSelection.value.length == 0) {
    ElMessage.error("请选择商品");
    return;
  }
  ElMessageBox.confirm(
    "你确定要删除么?不删除不行?再给你一次机会！！！好吧,那你删了吧",
    "警告",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }
  )
    .then(() => {
      deleteByIds(multipleSelection.value).then((res) => {
        if (res.data.code == 200) {
          ElMessage.success("删除成功");
          loadProdList();
        } else {
          ElMessage.error(res.data.msg);
        }
      });
    })
    .catch(() => {});
};
//添加商品
const onAddProd = () => {
  form.value = {
    appr: "",
    brandId: null,
    prodId: null,
    prodImage: "",
    prodKind: null,
    prodName: "",
    prodSpu: "",
    prodType: null,
    tagId: null,
    unitId: null,
  };
  dialogFormVisible.value = true;
};
//加载页面钩子函数
onMounted(() => {
  getDictList(1).then((res) => {
    if (res.data.code == 200) {
      deptList.value = res.data.data;
    }
  });
  getDictList(2).then((res) => {
    if (res.data.code == 200) {
      unitList.value = res.data.data;
    }
  });
  getDictList(3).then((res) => {
    if (res.data.code == 200) {
      tagList.value = res.data.data;
    }
  });

  getBrandList(brandForm.value).then((res) => {
    if (res.data.code == 200) {
      brandList.value = res.data.data.records;
    }
  });
  selectType().then((res) => {
    if (res.data.code == 200) {
      typeList.value = res.data.data;
    }
  });
  loadProdList();
});
</script>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
